package com.geezdata.cps.sdk3rd.wechat.method;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.geezdata.cps.sdk3rd.wechat.request.WechatMiniProgramTemplateMessageRequest;
import com.geezdata.cps.sdk3rd.wechat.response.WechatMiniProgramTemplateMessageResult;
import com.google.common.collect.Maps;

/**
 * @Author: sszheng
 * @Date: 2018/7/31 15:37
 */
public class WechatMiniProgramTemplateMessage extends BaseWechat implements Wechat<WechatMiniProgramTemplateMessageRequest, WechatMiniProgramTemplateMessageResult> {
    private static final String URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=";

    private Map<String, Object> prepareParams(WechatMiniProgramTemplateMessageRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        Map<String, Object> dataMap = prepareDataParams(request);
        map.put("touser", request.getTouser());
        map.put("template_id", request.getTemplateId());
        if(request.getPage() != null) {
            map.put("page", request.getPage());
        }
        map.put("form_id", request.getFormId());

        if(dataMap.size() > 0) {
            map.put("data", dataMap);
        }

        return map;
    }

    private Map<String,Object> prepareDataParams(WechatMiniProgramTemplateMessageRequest request) {
        Map<String, Object> dataMap = Maps.newHashMap();
        setKeyword(dataMap,"keyword1", request.getKeyword1());
        setKeyword(dataMap,"keyword2", request.getKeyword2());
        setKeyword(dataMap,"keyword3", request.getKeyword3());
        setKeyword(dataMap,"keyword4", request.getKeyword4());
        setKeyword(dataMap,"keyword5", request.getKeyword5());
        setKeyword(dataMap,"keyword6", request.getKeyword6());
        setKeyword(dataMap,"keyword7", request.getKeyword7());
        setKeyword(dataMap,"keyword8", request.getKeyword8());
        setKeyword(dataMap,"keyword9", request.getKeyword9());
        setKeyword(dataMap,"keyword10", request.getKeyword10());
        return dataMap;
    }

    private void setKeyword(Map<String, Object> dataMap, String key, String value) {
        if(StringUtils.isEmpty(value)) {
            return ;
        }
        Map<String, Object> valueMap = Maps.newHashMap();
        valueMap.put("value", value);
        dataMap.put(key,  valueMap);
    }


    @Override
    public WechatMiniProgramTemplateMessageResult execute(WechatMiniProgramTemplateMessageRequest request) {
        Map<String, Object> params = prepareParams(request);
        return doPost(URL + request.getToken(), params, WechatMiniProgramTemplateMessageResult.class);
    }
}
